# coding: utf-8

import os
import sys

import config
from initialize import logger

reload(sys)
sys.setdefaultencoding('utf-8')


def initialize():
    ''' 初始化目录 '''
    if not os.path.exists(config.DATA_DIRECTORY):
        os.mkdir(config.DATA_DIRECTORY)
    if not os.path.exists(config.LOG_DIRECTORY):
        os.mkdir(config.LOG_DIRECTORY)
    ''' 初始化参数 '''
    from optparse import OptionParser
    optionparser = OptionParser(description="chinese people's insurance [insurance policy] crawler",
                                prog="chinese people's insurance [insurance policy] crawler",
                                version='0.1', usage='%prog [starting ][action]')
    optionparser.add_option('-f', '--filename',
                            action='store', type='string', dest='filename', default=None,
                            help=u'查询数据存放文件, 格式:身份证|保单号, 每行一次查询')
    option, args = optionparser.parse_args()
    initialize_message = 'input is option={0} args={1}'.format(option, args)
    logger.info(size=len(initialize_message))
    logger.info(initialize_message, split=True)
    return option


def main():
    option = initialize()
    from handler.file import FileHandler
    from spider import RenbaoSpider, ZhonghuaSpider, TaipingyangSpider
    file_handler = FileHandler()
    query_list = file_handler.read_querying(option.filename)
    if not query_list:
        logger.info('query list not empty!')
        exit()

    renbao_spider = RenbaoSpider(file_handler=file_handler)
    zhonghua_spider = ZhonghuaSpider(file_handler=file_handler)
    taipingyang_spider = TaipingyangSpider(file_handler=file_handler)

    def get_spider(policy_no):
        ''' 根据保单号获取对应爬虫 '''
        char = policy_no[0:1]
        # dic = {'P': renbao_spider, '0': zhonghua_spider, 'A': taipingyang_spider}
        dic = {'P': None, '0': None, 'A': taipingyang_spider}
        return dic.get(char, None)

    def run(querys):
        ''' 单条执行 '''
        for query in querys:
            idcard_no, policy_no = query
            spider = get_spider(policy_no)
            if spider is None:
                continue
            spider.run(policy_no, idcard_no)

    def batch_run(querys):
        ''' 批量执行 '''
        spider_group = [ [],[],[] ]
        for query in querys:
            policy_no = query[1]
            spider = get_spider(policy_no)
            if spider == renbao_spider:
                index = 0
            elif spider == zhonghua_spider:
                index = 1
            elif spider == taipingyang_spider:
                index = 2
            else:
                continue
            spider_group[index].append(query)
        spider_names = ('renbao', 'zhonghua', 'taipingyang')
        for (index, spider_query) in enumerate(spider_group):
            logger.info('spider {0} start...'.format(spider_names[index]), split=True)
            if index == 0:
                renbao_spider.batch_run(spider_query)
            elif index == 1:
                zhonghua_spider.batch_run(spider_query)
            elif index == 2:
                taipingyang_spider.batch_run(spider_query)
            else:
                continue
    run(query_list)
    # batch_run(query_list)


if __name__ == '__main__':
    main()
